package chen.huai.jie.spring.xmlconfig.mybatis;

import org.apache.ibatis.type.TypeHandler;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

public class InsertBuilder implements SqlBuilder {
    public InsertBuilder() {
    }

    public String buildSql(Class<?> mapper, Method method, EntityPortray entityPortray) {
        StringBuilder builder = new StringBuilder();
        Map<String, Class<?>> typeMap = entityPortray.getColumnTypeMap();
        Map<String, String> columnMap = entityPortray.getColumnMap();
        Map<String, Class<? extends TypeHandler>> typeHandlers = entityPortray.getColumnTypeHandlers();
        Map<String, Class<?>> parameterMap = MapperUtils.getParameters(method);
        builder.append("<script>insert into ").append(entityPortray.getName()).append((String) columnMap.values().stream().collect(Collectors.joining(",", "(", ")"))).append(" values ");
        Map.Entry<String, Class<?>> parameter = (Map.Entry) parameterMap.entrySet().iterator().next();
        if (parameter == null) {
            throw new RuntimeException("Insert needs parameter");
        } else {
            if (Collection.class.isAssignableFrom((Class) parameter.getValue())) {
                builder.append("<foreach collection=\"collection\" item=\"item\" index=\"index\" separator=\",\">").append((String) typeMap.entrySet().stream().map((e) -> {
                    return MapperUtils.buildTypeValue((String) e.getKey(), (Class) e.getValue(), "item.", (Class) typeHandlers.get(e.getKey()));
                }).collect(Collectors.joining(",", "(", ")"))).append("</foreach>");
            } else {
                builder.append((String) typeMap.entrySet().stream().map((e) -> {
                    return MapperUtils.buildTypeValue((String) e.getKey(), (Class) e.getValue(), "", (Class) typeHandlers.get(e.getKey()));
                }).collect(Collectors.joining(",", "(", ")")));
            }

            builder.append("</script>");
            return builder.toString();
        }
    }
}
